package com.sh.business.listener;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.sh.business.domain.User;
import com.sh.business.domain.vo.BizUserImportVo;
import com.sh.business.mapper.UserMapper;
import com.sh.common.core.exception.ServiceException;
import com.sh.common.core.utils.SpringUtils;
import com.sh.common.core.utils.StringUtils;
import com.sh.common.excel.core.ExcelListener;
import com.sh.common.excel.core.ExcelResult;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * 系统用户自定义导入
 *
 * @author ruoyi
 */
@Slf4j
public class BizUserImportListener extends AnalysisEventListener<BizUserImportVo> implements ExcelListener<BizUserImportVo> {

    private final UserMapper userMapper;


    private int successNum = 0;
    private int failureNum = 0;
    private final StringBuilder successMsg = new StringBuilder();
    private final StringBuilder failureMsg = new StringBuilder();

    public BizUserImportListener() {
        this.userMapper = SpringUtils.getBean(UserMapper.class);;
    }


    @Override
    public void invoke(BizUserImportVo userVo, AnalysisContext context) {
        if (ObjectUtil.isNull(userVo.getParentWalletAddress())) {
            return;
        }
        User user = userMapper.queryByWalletAddress(userVo.getWalletAddress());
        if (ObjectUtil.isNotNull(user)) {
            log.error("用户已存在:{}", userVo.getWalletAddress());
            return;
        }
        User parentUser = userMapper.queryByWalletAddress(userVo.getParentWalletAddress());
        if (ObjectUtil.isNull(parentUser)) {
            log.error("推荐人不存在:{}", userVo.getParentWalletAddress());
            return;
        }
        user = new User();
        user.setWalletAddress(userVo.getWalletAddress());
        user.setParentId(parentUser.getUserId());
        user.setParentWalletAddress(userVo.getParentWalletAddress());
        String ancestors = parentUser.getAncestors() + StringUtils.SEPARATOR + parentUser.getUserId();
        // 去除0，
        ancestors = StringUtils.removeStart(ancestors, "0,");
        user.setAncestors(ancestors);

        userMapper.insert(user);


        /*SysUserVo sysUser = this.userService.selectUserByUserName(userVo.getUserName());
        try {
            // 验证是否存在这个用户
            if (ObjectUtil.isNull(sysUser)) {
                SysUserBo user = BeanUtil.toBean(userVo, SysUserBo.class);
                ValidatorUtils.validate(user);
                user.setPassword(password);
                user.setCreateBy(operUserId);
                userService.insertUser(user);
                successNum++;
                successMsg.append("<br/>").append(successNum).append("、账号 ").append(user.getUserName()).append(" 导入成功");
            } else if (isUpdateSupport) {
                Long userId = sysUser.getUserId();
                SysUserBo user = BeanUtil.toBean(userVo, SysUserBo.class);
                user.setUserId(userId);
                ValidatorUtils.validate(user);
                userService.checkUserAllowed(user.getUserId());
                userService.checkUserDataScope(user.getUserId());
                user.setUpdateBy(operUserId);
                userService.updateUser(user);
                successNum++;
                successMsg.append("<br/>").append(successNum).append("、账号 ").append(user.getUserName()).append(" 更新成功");
            } else {
                failureNum++;
                failureMsg.append("<br/>").append(failureNum).append("、账号 ").append(sysUser.getUserName()).append(" 已存在");
            }
        } catch (Exception e) {
            failureNum++;
            String msg = "<br/>" + failureNum + "、账号 " + userVo.getUserName() + " 导入失败：";
            failureMsg.append(msg).append(e.getMessage());
            log.error(msg, e);
        }*/
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {

    }

    @Override
    public ExcelResult<BizUserImportVo> getExcelResult() {
        return new ExcelResult<>() {

            @Override
            public String getAnalysis() {
                if (failureNum > 0) {
                    failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
                    throw new ServiceException(failureMsg.toString());
                } else {
                    successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
                }
                return successMsg.toString();
            }

            @Override
            public List<BizUserImportVo> getList() {
                return null;
            }

            @Override
            public List<String> getErrorList() {
                return null;
            }
        };
    }
}
